import { expect } from '@jest/globals';
import fs from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};
const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble
};

const versionConversion = (v: string) => {
  let version = v.replace(/\b(\d{1,2})\b/g, function (_, match) {
    return String(match).padStart(2, '0');
  });
  version = version.replace(/\((\d{1,2})\)/g, function (_, match) {
    return `(${String(match).padStart(3, '0')})`;
  });
  return parseInt(version.replace(/[.()]/g, ''));
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const dataRoot = await fs.readFile(path.resolve(projectRoot, 'build-profile.json5'));

  // 解析JSON5文件
  const objRoot = JSON5.parse(dataRoot.toString());

  // 修改对象
  objRoot.app.products = [{
    ...objRoot.app.products[0],
    targetSdkVersion: objRoot.app.products[0].compileSdkVersion
  }];

  // 将对象转换回JSON5字符串
  const json5ToStr = JSON5.stringify(objRoot);

  // 将修改后的字符串写回文件
  await fs.writeFile(path.resolve(projectRoot, 'build-profile.json5'), json5ToStr, 'utf8');

  // 获取version
  const compatibleSdkVersionObj = objRoot.app.products[0].compatibleSdkVersion;

  // 通过规则转换version
  const compatibleVersion = versionConversion(compatibleSdkVersionObj);
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
    ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);

  // 获取config.json配置
  const dataEntry = await fs.readFile(
    path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/intermediates/res/default/module.json')
  );
  const objEntry = JSON5.parse(dataEntry.toString());
  objEntry.app = {
    ...objEntry.app,
    version: objEntry.app.compileSdkVersion
  };

  // 将对象转换回JSON5字符串
  const jsonToStr = JSON.stringify(objEntry);

  // 将修改后的字符串写回文件
  await fs.writeFile(path.resolve(project.getModule('entry').moduleRootPath(), 'build/default/intermediates/res/default/module.json'), jsonToStr, 'utf8');

  const { compileSdkType, targetAPIVersion, minAPIVersion } = objEntry.app;
  const bool =
    minAPIVersion === compatibleVersion &&
    compileSdkType === 'HarmonyOS';
  record.addStep('执行hap编译构建', result);
  expect(minAPIVersion).toBe(compatibleVersion);
  expect(bool).toBe(true);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_BUILD_ONESDK_MANAGER_STAGE_018')
  .description('hos工程compileSdkVersion、compatibleSdkVersion、targetSdkVersion为字符串且格式正确')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun('entry'))
  .load();
